package com.etc.utils;

import com.etc.dao.SysUserDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author kalista
 * @Description
 * @Date 2020/12/18  9:30
 **/
public class MybaitsUtils {


    private static SqlSessionFactory factory = null;

    static  ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();

    /**
     * 多线程访问一个共享变量是不是对出现并发问题。 特别是多个线程对一个变量进行写入的时候。ThreadLoacl 多线程访问出现的
     * 线程不安全问题，
     */

    //初始化SqlSessionFactory
    static {
        String resouce = "SqlMapConfig.xml";
        try {
            // 配置文件
            InputStream resourceAsStream = Resources.getResourceAsStream(resouce);
            // 使用sqlsesionFactoryBuilder从xml中配置文件创建
            factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static  SqlSession openSession(){
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession == null){
            sqlSession = factory.openSession();
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }


    public static  void close(SqlSession sqlSession){
        if (sqlSession != null){
            threadLocal.remove();
            sqlSession.close();
        }
    }

}
